import { getReadCardToken } from "@/api/common/other/index";

//const default_url = "ws://192.168.110.14:21802/reader";
const default_url = "ws://127.0.0.1:21802/reader";
const store_url = ref("");

const heartbeatMessage = "ping";

/*
readyState:
	CONNECTING: 0;
	CLOSING: 2;
	CLOSED: 3;
*/
let readyState: number;
let socket: WebSocket;
const cardInfo = ref();
let token: any;

function myEventHandler(err: any) {
  alert("设备连接失败，请检查设备");
}

export function useToDeviceSocket(errorCallBack: any) {
  function connet(url?: string | null) {
    store_url.value = url ? url : default_url;
    socket = new WebSocket(store_url.value);
    socket.onerror = errorCallBack || myEventHandler;
    socket.onclose = errorCallBack;
  }

  function onOpen(callback: any, detail: any, code?: string) {
    socket.onopen = callback
      ? callback
      : () => {
          readyState = socket.readyState;
          if (socket.readyState === 1) {
            if (detail === "common") {
              getReadCardToken(code)
                .then((res) => {
                  if (res.success) {
                    token = res.data;
                    sendMessage(token);
                  } else {
                    errorCallBack();
                    ElMessage({
                      type: "warning",
                      message: "获取token失败",
                    });
                  }
                })
                .finally(() => {
                  errorCallBack();
                });
            } else {
              getReadCardToken()
                .then((res) => {
                  if (res.success) {
                    token = res.data;
                    sendMessage(token);
                  } else {
                    errorCallBack();
                    ElMessage({
                      type: "warning",
                      message: "获取token失败",
                    });
                  }
                })
                .finally(() => {
                  errorCallBack();
                });
            }
          } else {
            ElMessage({
              type: "warning",
              message: "请检查设备连接!",
            });
          }
        };
  }

  function onMessage(callback: any) {
    socket.onmessage = callback
      ? callback
      : (e) => {
          let result = JSON.parse(e.data);
          let { success, msg, data } = result;
          if (!success) {
            ElMessage.error(msg);
            return;
          }
          cardInfo.value = data;
        };
  }

  function onClose(callback: any) {
    socket.onclose = callback
      ? callback
      : (e) => {
          console.log("onClose", e);
        };
  }

  function sendMessage(msg: any) {
    if (socket && socket.readyState === 1) {
      socket.send(`read:${msg}:smz`);
    }
  }

  function onError(callback: any) {
    socket.onerror = callback
      ? callback
      : (e) => {
          console.log("WebSocket onError disconnected", e);
          // 重新连接
          let resetCon = setInterval(() => {
            if (socket.readyState !== 1) {
              connet(store_url.value);
            } else {
              clearInterval(resetCon);
            }
          }, 3000);
        };
  }

  function handleClose() {
    if (socket && socket.readyState === 1) {
      socket.close();
    }
  }

  return {
    connet,
    onOpen,
    onMessage,
    onClose,
    sendMessage,
    onError,
    handleClose,
    socket,
    cardInfo,
    readyState,
    token,
  };
}
